//
//  ViewController.m
//  HTTPTest
//
//  Created by youbing on 2017/2/6.
//  Copyright © 2017年 youbing. All rights reserved.
//
//weakSelf
#define weak_Self(id) __weak typeof(id) _self = id
#define WEAK_SELF __weak typeof(self) _self = self

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIProgressView *downloadingProgressView;
@property (weak, nonatomic) IBOutlet UILabel *downloadLbl;
@property (nonatomic, strong) NSData *currentData;/**<当前下载的data*/
@property (nonatomic, strong) NSURLSession *currentSession;/**<当前会话*/


@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;/**<*/
@end

@implementation ViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}
#pragma mark - button Methods
// 普通下载
- (IBAction)beginBtnClick {
    [self getImage];
}
// 断点 - 开始
- (IBAction)resumeDownloadBegin:(id)sender {
    if (self.currentData) {
        self.downloadTask = [self.currentSession downloadTaskWithResumeData:self.currentData];
        [self.downloadTask resume];
    }else{
        [self getImage];
    }
}
// 断点 - 暂停
- (IBAction)downloadSuspend:(id)sender {
    WEAK_SELF;
    [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        _self.currentData = resumeData;
        _self.downloadTask = nil;
    }];
}
// 取消
- (IBAction)endBtnClick {
    [self.downloadTask cancel];
    self.downloadTask = nil;
    self.downloadLbl.text = @"0.0%";
    self.downloadingProgressView.progress = 0;
}

#pragma mark - NSURLSession Test
- (void)getImage{
    NSURL *url = [NSURL URLWithString:@"http://img-download.pchome.net/download/1k1/2w/41/of2txd-1a6l.jpg"];
    NSURLRequest  *request = [NSURLRequest requestWithURL:url];
    self.downloadTask = [self.currentSession downloadTaskWithRequest:request];
    self.imageView.image = nil;
    [self.downloadTask resume];
}

#pragma mark  NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
    
}

- (void)URLSession:(NSURLSession *)session
                 downloadTask:(NSURLSessionDownloadTask *)downloadTask
                 didWriteData:(int64_t)bytesWritten
            totalBytesWritten:(int64_t)totalBytesWritten
    totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
//     计算当前下载进度并更新视图
    double downloadProgress = totalBytesWritten / (double)totalBytesExpectedToWrite;
    [self setDownloadProgress:downloadProgress];
}
//     NSURLSessionTaskDelegate -- 均调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error{
    NSLog(@"-----请求完成------");
    
}

#pragma mark - upload UI
- (void)setDownloadProgress:(double)progressValue{
    WEAK_SELF;
    NSString *progressStr = [NSString stringWithFormat:@"%.1f", progressValue * 100];
    progressStr = [progressStr stringByAppendingString:@"%"];
    NSLog(@"DownloadProgress %f",progressValue);
    dispatch_async(dispatch_get_main_queue(), ^{
        _self.downloadingProgressView.progress = progressValue;
        _self.downloadLbl.text = progressStr;
    });
}

#pragma mark - get
- (NSURLSession *)currentSession{
    if (!_currentSession) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _currentSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _currentSession;
}
@end
